package com.vf.cloud.common.listener;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.vf.cloud.common.domain.Config;
import com.vf.cloud.common.domain.Dict;
import com.vf.cloud.common.domain.Gpu;
import com.vf.cloud.common.domain.Server;
import com.vf.cloud.common.domain.User;
import com.vf.cloud.common.pool.ProssPool;
import com.vf.cloud.common.util.EncryptUtil;
import com.vf.cloud.common.util.GpuUtil;
import com.vf.cloud.common.util.UuidUtil;
import com.vf.cloud.common.vo.GpuVo;
import com.vf.cloud.common.vo.RelayVo;
import com.vf.cloud.server.adapter.AdapterServer;
import com.vf.cloud.server.colony.MasterServer;
import com.vf.cloud.server.colony.NodeServer;
import com.vf.cloud.server.mysql.MySQLServer;
import com.vf.cloud.server.nginx.NginxServer;
import com.vf.cloud.server.relay.RelayServer;
import com.vf.cloud.server.signalling.SignallingServer;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

	@Override
	public void onApplicationEvent(ApplicationReadyEvent contextReadyEvent) {
		

		boolean isOk = MySQLServer.getInstance().run();
		if (!isOk) {
			log.error("启动基础服务mysql失败，请联系管理员.");
			return;
		}

		User user = User.dao.findbyUsername("admin");
		if (user == null) {
			user = new User();
			user.setId(UuidUtil.getUUID());
			user.setName("超级管理员");
			user.setUsername("admin");
			user.setPassword(EncryptUtil.encrypt("Xxc@admin2022"));
			if (!user.save()) {
				log.error("创建默认用户失败，请联系管理员.");
				return;
			}
		}
		
		//初始化系统必备字典
		Dict dict = Dict.dao.findByCode("Industry");
		if(dict==null) {
			dict=new Dict();
			dict.setId(UuidUtil.getUUID());
			dict.setName("行业类型");
			dict.setCode("Industry");
			dict.setStatus("0");
			dict.setOrderNum(1);
			dict.save();
		}
		

		List<Server> servers = Server.dao.findAll();
		for (Server s : servers) {
			if (StrKit.equals("signaling", s.getType())) {
				SignallingServer.getInstance().restart(s);
			} else if (StrKit.equals("relay", s.getType())) {
				JSONObject object = JSONObject.parseObject(s.getConfig());
				if (!RelayServer.getInstance().verify(object)) {
					log.error(String.format("[%s]参数不完整，无法启动。", s.getName()));
					return;
				}

				if (StrKit.equals("1", s.getEnabled())) {
					RelayVo relayVo = new RelayVo();
					relayVo.setId(s.getId());
					relayVo.setIp(object.getString("ip"));
					relayVo.setStunPort(object.getInteger("stunPort"));
					relayVo.setTurnPort(object.getInteger("turnPort"));
					relayVo.setEnabled(object.getString("enabled"));
					relayVo.setUsername(object.getString("username"));
					relayVo.setPassword(object.getString("password"));
					relayVo.setEnabled(s.getEnabled());
					RelayServer.getInstance().restart(relayVo);
				} else {
					ProssPool.killByPort(object.getString("stunPort"));
					ProssPool.killByPort(object.getString("turnPort"));
				}

			}
		}

		getGraphicsInfo();
		AdapterServer.getInstance().init();
		
		
		Config config = Config.dao.findById("VFCloud_2022");
		if (config != null) {
			MasterServer.getInstance().restart(config);
			NodeServer.getInstance().restart(config);
		}
		

		/* ArtemisServer.getInstance().run(); */
		NginxServer.getInstance().run();

	}

	private void getGraphicsInfo() {
		List<Gpu> olds = Gpu.dao.findAll();
		Map<String, Gpu> map = new HashMap<String, Gpu>();
		for (Gpu g : olds) {
			map.put(g.getId(), g);
		}
		List<GpuVo> gpus = GpuUtil.getGPUs();
		for (GpuVo e : gpus) {
			if (!map.containsKey(e.getUuid())) {
				Gpu gpu = new Gpu();
				gpu.setId(e.getUuid());
				gpu.setName(e.getName());
				gpu.setMemoryTotal(e.getMemoryTotal());
				gpu.setBoardId(e.getBoardId());
				gpu.setVbiosVersion(e.getVbiosVersion());
				gpu.setLimit(1);
				gpu.setIndex(e.getModuleId());
				gpu.save();
			} else {
				Gpu gpu = new Gpu();
				gpu.setId(e.getUuid());
				gpu.setName(e.getName());
				gpu.setMemoryTotal(e.getMemoryTotal());
				gpu.setBoardId(e.getBoardId());
				gpu.setVbiosVersion(e.getVbiosVersion());
				gpu.setIndex(e.getModuleId());
				gpu.update();
				map.remove(e.getUuid());
			}
		}
		Iterator<String> it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			Gpu.dao.deleteById(key);
		}
	}
}
